from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView, ListView, RedirectView
from google.appengine.api import users
from apps.blog.models import Article
from apps.core.views import LoginRequiredMixin
from apps.dashboard.forms import ArticleForm, ArticleEditForm



class DashboardIndex(LoginRequiredMixin, ListView):
    template_name = 'dashboard/index.html'

    def get_queryset(self):
        return Article.all().order('-created_at')

    def get_context_data(self, **kwargs):
        data = super(DashboardIndex, self).get_context_data(**kwargs)
        data.update({
            'current_user': users.get_current_user()
        })

        return data


class DashboardArticleNew(LoginRequiredMixin, FormView):
    template_name = 'dashboard/article_form.html'
    form_class = ArticleForm

    def get_success_url(self):
        return reverse('dashboard-index')

    def form_valid(self, form):
        # save new Article
        article = Article(**form.cleaned_data)
        article.put()

        # show notification message
        message = _("New blog posted: \"%s\"" % form.cleaned_data.get('title'))
        messages.add_message(self.request, messages.SUCCESS, message)

        return super(DashboardArticleNew, self).form_valid(form)

    def form_invalid(self, form):
        message = _("Invalid form. Please check it.")
        messages.add_message(self.request, messages.ERROR, message)

        return super(DashboardArticleNew, self).form_invalid(form)


class DashboardArticleEdit(LoginRequiredMixin, FormView):
    template_name = 'dashboard/article_form.html'
    form_class = ArticleEditForm

    def get_initial(self):
        obj = self.get_object()
        data = {
            'title': obj.title,
            'slug': obj.slug,
            'content': obj.content,
            'is_published': obj.is_published
        }

        return data

    def get_success_url(self):
        return reverse('dashboard-index')

    def get_context_data(self, **kwargs):
        data = super(DashboardArticleEdit, self).get_context_data(**kwargs)
        data.update({
            'object': self.get_object()
        })

        return data

    def get_object(self, queryset=None):
        return Article.get(self.kwargs.get('key'))

    def form_valid(self, form):
        obj = self.get_object()

        # check slug validation.
        slug = form.cleaned_data.get('slug')
        if slug != obj.slug and Article.gql("WHERE slug = :1", slug).count():
            message = _("Slug should be unique.")
            messages.add_message(self.request, messages.ERROR, message)

            return super(DashboardArticleEdit, self).form_invalid(form)

        obj.title = form.cleaned_data.get('title')
        obj.slug = slug
        obj.is_published = form.cleaned_data.get('is_published')
        obj.put()

        message = _("Post updated.")
        messages.add_message(self.request, messages.SUCCESS, message)

        return super(DashboardArticleEdit, self).form_valid(form)

    def form_invalid(self, form):
        message = _("Invalid form. Please check it.")
        messages.add_message(self.request, messages.ERROR, message)

        return super(DashboardArticleEdit, self).form_invalid(form)


class DashboardArticleDelete(LoginRequiredMixin, RedirectView):
    permanent = False

    def get_object(self):
        return Article.get(self.kwargs.get('key'))

    def get_redirect_url(self, **kwargs):
        return reverse('dashboard-index')

    def get(self, request, *args, **kwargs):
        # delete object
        obj = self.get_object()
        title = obj.title
        obj.delete()

        # add message
        message = _("Deleted post, %s" % title)
        messages.add_message(request, messages.SUCCESS, message)

        return super(DashboardArticleDelete, self).get(
            request, *args, **kwargs)


class DashboardLogout(LoginRequiredMixin, RedirectView):
    permanent = False

    def get(self, request, *args, **kwargs):
        return redirect(users.create_logout_url(reverse('core-index')))
